package com.aliyuncs.aui.service.impl;

import com.aliyuncs.aui.common.utils.MySQLUtil;
import com.aliyuncs.aui.dto.res.TakeoutResponse;
import com.aliyuncs.aui.service.TakeoutService;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

@Slf4j
@Service
public class TakeoutServiceImpl implements TakeoutService {

    private final MySQLUtil mySQLUtil;

    public TakeoutServiceImpl(MySQLUtil mySQLUtil) {
        this.mySQLUtil = mySQLUtil;
    }

    @Override
    public TakeoutResponse createTakeoutation(String tenantId, String name, String addr, String tel, String state) {
        String takeoutId = UUID.randomUUID().toString();
        String sql = "INSERT INTO takeout (name, addr, tel, state, tenant_id, takeout_id) VALUES (?, ?, ?, ?, ?, ?)";
        
        try {
            mySQLUtil.executeUpdate(sql, name, addr, tel, state, tenantId, takeoutId);
            return TakeoutResponse.builder()
                    .code(200)
                    .message("创建成功")
                    .resvId(takeoutId)
                    .tenantId(tenantId)
                    .build();
        } catch (SQLException e) {
            log.error("创建外带失败", e);
            return TakeoutResponse.builder()
                    .code(500)
                    .message("创建失败")
                    .build();
        }
    }

    @Override
    public TakeoutResponse updateTakeoutationState(String takeoutId, String state) {
        String sql = "UPDATE takeout SET state = ? WHERE takeout_id = ?";
        
        try {
            int rows = mySQLUtil.executeUpdate(sql, state, takeoutId);
            if (rows > 0) {
                return TakeoutResponse.builder()
                        .code(200)
                        .message("更新成功")
                        .build();
            } else {
                return TakeoutResponse.builder()
                        .code(404)
                        .message("未找到对应外带")
                        .build();
            }
        } catch (SQLException e) {
            log.error("更新外带状态失败", e);
            return TakeoutResponse.builder()
                    .code(500)
                    .message("更新失败")
                    .build();
        }
    }
}
